<?php

namespace App\Http\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class FinanceProxy extends Base
{
    protected $financeProxytable = 'finance_proxy';// 代充管理
    protected $financeProxyOrderTable = 'finance_proxy_order';// 代充管理订单表
    protected $financeProxyStreamTable = 'finance_proxy_stream';// 代充管理流水表
    protected $redis_finance_proxy = 'FINANCE:PROXY:ORDER:NUMBER';
    protected $primaryKey = "proxy_id";

    public function __construct(array $attributes = [])
    {
        parent::__construct($this->financeProxytable, $attributes);
    }

    /*
     * 代充信息相关Model
     * */

    //获取代充信息
    public function getProxyInfoByUserId($userId)
    {
        $document = DB::table($this->financeProxytable)
            ->where(["user_id" => $userId])
            ->first();

        return self::objToArray($document);
    }


    //获取代充锁定金额
    public function getProxyLockAmountByUserId($userId)
    {
        $sum = DB::table($this->financeProxyOrderTable)
            ->where(["user_id" => $userId, "status" => 1])
            ->sum("amount");

        return intval($sum);
    }

    /**
     * 修改用户金额
     * @param $userId
     * @param $amount
     * @return bool
     */
    public function incFinanceProxy($userId, $amount)
    {
        // 变更钱包
        DB::table($this->financeProxytable)
            ->where(['user_id' => $userId])
            ->increment('balance', $amount);
        return true;
    }

    /**
     * 获取配置
     * @param $id
     * @return array|mixed
     */
    public function getFinanceProxyById($id){
        $result = DB::table($this->financeProxytable)
            ->where($this->primaryKey, '=', $id)
            ->first();
        if (empty($result)){
            return [];
        }
        $result = $this->objToArray($result);
        return $result;
    }

    /**
     * 代充管理-创建/更新/删除
     *
     * @param array $data 数据
     * @param string $type 操作类型 默认 insert=创建，update=更新
     * @param int $id
     * @return bool
     * */
    public function CUDFinanceProxy($data = [], $type = 'insert', $id = 0)
    {
        switch ($type) {
            case 'insert':
                $ret = DB::table($this->financeProxytable)->insertGetId($data);
                break;
            case 'update':
                $ret = DB::table($this->financeProxytable)->where([$this->primaryKey => $id])->update($data);
                break;
            case 'delete':
                $ret = DB::table($this->financeProxytable)->where([$this->primaryKey => $id])->delete();
                break;
            default:
                $ret = false;
                break;
        }

        return $ret;
    }

    /*
     * 代充订单相关Model
     * */

    /**
     * 创建订单
     * @param $userId
     * @param $toUserId
     * @param $type
     * @param $amount
     * @param $status
     * @return bool
     */
    public function createFinanceProxyOrder($userId, $toUserId, $type, $amount, $status)
    {
        // 查询钱包
        $wallet = DB::table($this->financeProxytable)
            ->where('user_id', '=', $userId)
            ->first(['balance']);

        $orderSn = create_recharge_order_sn();

        // 创建订单
        $orderId = DB::table($this->financeProxyOrderTable)->insertGetId([
            "user_id" => $userId,
            "to_user_id" => $toUserId,
            "type" => $type,
            "amount" => $amount,
            "status" => $status,
            "balance" => $wallet->balance + $amount,
            "order_sn" => $orderSn,
            "created_at" => time(),
            "updated_at" => time()
        ]);

        Redis::HINCRBY($this->redis_finance_proxy, $toUserId, 1); //更新未读数

        return ["order_sn" => $orderSn, "order_id" => $orderId];
//        return true;
    }

    // 订单列表
    public function getFinanceProxyOrderListData($condition, $page, $limit)
    {
        // 总条数
        $totalCount = DB::table($this->financeProxyOrderTable)
            ->where($condition)
            ->count();

        $data = DB::table($this->financeProxyOrderTable)
            ->where($condition)
            ->orderBy('order_id', 'desc')
            ->offset($page * $limit)
            ->limit($limit)
            ->get(['order_id', 'order_sn', 'user_id', 'to_user_id', 'type', 'status', 'amount', 'created_at']);

        return $this->checkPageData($page, $limit, $totalCount, self::objToArray($data));
    }

    //获取代充订单信息
    public function getProxyOrderInfoByOrderId($orderId)
    {
        $document = DB::table($this->financeProxyOrderTable)
            ->where(["order_id" => $orderId])
            ->first();

        return self::objToArray($document);
    }

    //更新订单状态
    public function updateOrderStatusByOrderId($orderId, $status, $optId = 0)
    {
        $document = DB::table($this->financeProxyOrderTable)
            ->where(["order_id" => $orderId])
            ->update(["status" => $status, "updated_at" => time(), "opt_id" => $optId]);

        return self::objToArray($document);
    }

    //重置订单红点
    public function resetFinanceProxyOrderNoticeNum($userId)
    {
        Redis::HDEL($this->redis_finance_proxy, $userId); //更新未读数
    }


    /*
     * 代充流水相关Model
     * */

    // 流水列表
    public function getFinanceProxyStreamListData($condition, $page, $limit)
    {
        // 总条数
        $totalCount = DB::table($this->financeProxyStreamTable)
            ->where($condition)
            ->count();

        $data = DB::table($this->financeProxyStreamTable)
            ->where($condition)
            ->orderBy('stream_id', 'desc')
            ->offset($page * $limit)
            ->limit($limit)
            ->get();

        return $this->checkPageData($page, $limit, $totalCount, self::objToArray($data));
    }

    /**
     * 创建流水
     * @param $userId
     * @param $toUserId
     * @param $type
     * @param $amount
     * @param $orderId
     * @return bool
     */
    public function createFinanceProxyStream($userId, $toUserId, $type, $amount, $orderId, $optId = 0 ,$kk_value=0,$price=0)
    {
        // 查询钱包
        $wallet = DB::table($this->financeProxytable)
            ->where('user_id', '=', $userId)
            ->first(['balance']);

        // 创建
        DB::table($this->financeProxyStreamTable)->insert([
            "user_id" => $userId,
            "to_user_id" => $toUserId,
            "type" => $type,
            "amount" => $amount,
            "order_id" => $orderId,
            "opt_id" => $optId,
            "balance" => $wallet->balance ,
            "kk_value" =>$kk_value ,
            "price" =>$price
        ]);

        return true;
    }

    public function getRedisFinanceProxyNumber($userId)
    {
        $ret = Redis::HGET($this->redis_finance_proxy, $userId);
        return !empty($ret) ? intval($ret) : 0;
    }

    public function getStockStream($user_id ,$page ,$pageSize){
        $res = DB::table($this->financeProxyStreamTable)
            ->where('type' ,3)
            ->where('user_id' ,$user_id)
            ->orderBy('stream_id', 'desc')
            ->offset($page * $pageSize)
            ->limit($pageSize)
            ->get();
        $data = $this->objToArray($res);
        foreach ($data as &$d){
            $d['kk_value'] = $d['kk_value']/100;
        }
        return $data;
    }
}
